package fun.tan90.test;


import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import fun.tan90.rt.RouteTrainComputer;
import fun.tan90.rt.RouteTrainData;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.client.IMqttClientConnectListener;
import org.dromara.mica.mqtt.core.client.MqttClient;
import org.noear.snack.ONode;
import org.tio.core.ChannelContext;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;

@Slf4j
public class RouteTrainDemo {

    private final static MqttClient MQTT_CLIENT = MqttClient.create()
            .ip("180.107.109.102")
            .port(1883)
            .username("admin")
            .password("nttieren0513")             // 密码
            .clientId("sailboat_phone_" + new Random().nextInt(1000))
            .keepAliveSecs(10)
            .reInterval(3000)
            .connectListener(new IMqttClientConnectListener() {
                @Override
                public void onConnected(ChannelContext context, boolean isReconnect) {
                    log.info("与链接服务器成功连接...");
                }

                @Override
                public void onDisconnect(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) {
                    log.info("与链接服务器断开连接...");
                }
            })
            .connectSync();

    public static void main(String[] args) {

        // 标位训练数据
        BiConsumer<Date, RouteTrainData> routeTrainDataBiConsumer = (ts, routeTrainData) -> {
            // TODO 发布到主题 mobile/up/route-train/{tenantCode}/{levelId}/{mHmId}
            log.info("发布训练数据=>{}", JSONUtil.toJsonStr(routeTrainData, JSONConfig.create().setIgnoreNullValue(false)));
        };

        AtomicReference<RouteTrainComputer> routeTrainComputer = new AtomicReference<>();

        MQTT_CLIENT.subQos1("pad/up/buoy/#", (context, topic, message, payload) -> {
            String payloadStr = new String(payload, StandardCharsets.UTF_8);
            log.info(payloadStr);
            ONode node = ONode.loadStr(payloadStr);
            String buoyType = node.get("buoyType").getString();
            if ("22".equals(buoyType)) {
                ONode buoyNode = node.get("buoy");
                ONode s1LatLon = buoyNode.get("s1LatLon").asArray();
                ONode s2LatLon = buoyNode.get("s2LatLon").asArray();
                ONode s0LatLon = buoyNode.get("s0LatLon").asArray();
                ONode buoyLatLon = buoyNode.get("buoyLatLon").asArray();

                double lat1 = s1LatLon.get(0).getDouble();
                double lon1 = s1LatLon.get(1).getDouble();

                double lat2 = s2LatLon.get(0).getDouble();
                double lon2 = s2LatLon.get(1).getDouble();

                double lat0 = s0LatLon.get(0).getDouble();
                double lon0 = s0LatLon.get(1).getDouble();

                double latBuoy = buoyLatLon.get(0).getDouble();
                double lonBuoy = buoyLatLon.get(1).getDouble();

                int buoyS0Dis = buoyNode.get("buoyS0Dis").getInt();
                int buoySide = buoyNode.get("buoySide").getInt();

                int roundMarkDis = node.get("roundMarkDis").getInt();
                int trainingLaps = node.get("trainingLaps").getInt();
                if (Objects.isNull(routeTrainComputer.get())) {
                    log.info("初始化 RouteTrainComputer对象");
                    RouteTrainComputer trainComputer = new RouteTrainComputer(routeTrainDataBiConsumer, 200,
                            lat1, lon1, lat2, lon2,
                            lat0, lon0, latBuoy, lonBuoy, buoyS0Dis, buoySide,
                            roundMarkDis, trainingLaps);
                    routeTrainComputer.compareAndSet(null, trainComputer);
                } else {
                    log.info("更新 RouteTrainComputer对象");
                    routeTrainComputer.get().updateParam(lat1, lon1, lat2, lon2,
                            lat0, lon0, latBuoy, lonBuoy, buoyS0Dis, buoySide,
                            roundMarkDis, trainingLaps);
                }
            }
        });

        MQTT_CLIENT.subQos1("pad/up/route-train/#", (context, topic, message, payload) -> {
            String payloadStr = new String(payload, StandardCharsets.UTF_8);
            log.info(payloadStr);
            ONode node = ONode.loadStr(payloadStr);
            String exeType = node.get("exeType").getString();
            if ("00".equals(exeType)) {
                log.info("训练开始，等待抢航触发");
                return;
            }
            if ("30".equals(exeType)) {
                log.info("训练停止，重置标位训练数据");
                routeTrainComputer.get().reset();
                return;
            }
            String trainId = node.get("trainId").getString();
            int remainTime = node.get("remainTime").getInt();
            int trainTime = node.get("trainTime").getInt();
            // TODO 获取帆船当前最新的GPS
            routeTrainComputer.get().compute(trainId, exeType, remainTime, trainTime, 31.128603, 122.107073);
        });

        ThreadUtil.sleep(1, TimeUnit.DAYS);
    }
}
